<template>
    <div class="table store sever_list">
        <div class="crumbs store_title">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>人员管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-select
                style="margin-top: 10px;width: 120px;"
                @change="timeSelectFn"
                v-model="searchTime"
                placeholder="时间类型"
            >
                <el-option label="下单时间" value="ORDERTIME"></el-option>
                <el-option label="操作时间" value="ORERATIONTIME"></el-option>
            </el-select>
            <el-date-picker
                :clearable="false"
                v-model="findStartTimeValue"
                @change="dataSelectFn"
                :picker-options="pickerOptAll"
                type="datetimerange"
                style="margin-bottom: 20px"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
            <!--<span class="sp-divleft"></span>-->
            <!--<div class="sp-div">-->
                <!--<el-button v-for="item in list" class="sp-btn" @click="editFn(item.id)">{{item.name}}</el-button>-->
            <!--</div>-->
            <el-table :data="list" show-summary border :summary-method="getSummaries" style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column prop="name" label="姓名">
                </el-table-column>
                <el-table-column prop="dereceiveNum" label="总接收" >
                </el-table-column>
                <el-table-column prop="somereceiveNum" label="已接收" >
                </el-table-column>
                <el-table-column prop="receiveNum" label="未跟踪" >
                </el-table-column>
                <el-table-column prop="addWechatNum" label="加微数" >
                </el-table-column>
                <el-table-column prop="invalidNum" label="无效数" >
                </el-table-column>
                <el-table-column prop="tailAfterNum" label="跟踪数" >
                </el-table-column>
                <el-table-column prop="repeatNum" label="重复数" >
                </el-table-column>
                <el-table-column prop="errorNum" label="异常数" >
                </el-table-column>
                <el-table-column prop="rate" label="通过率" >
                </el-table-column>
                <el-table-column prop="rateAll" label="总通过率" >
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <!--<el-button size="small" type="primary" @click="bandFn(scope.$index, scope.row)">详情</el-button>-->
                        <el-button size="small" type="primary" @click="editFn(scope.$index, scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog :visible.sync="addPeopleDialog" width="600px">
            <el-form label-width="100px" ref="addForm_data" :model="addForm_data" class="extend_form">
                <el-button style="display: block;margin-bottom: 20px;" type="primary" @click="addData_ex">添加负责区域</el-button>
                <div class="ex_parent" v-for="(item, index) in data_extend" :key="index">
                    <div>
                        <el-form-item label="人员姓名：">
                            <el-input v-model='item.name' disabled class="ex_input_f"></el-input>
                        </el-form-item>
                        <el-form-item label="推广省份：">
                            <el-select v-model="item.province" class="ex_input_y mr10" placeholder="省" @change="getProareaList(item.province,index)">
                                <el-option v-for="items in provinceData"  :value="items" :key="items.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="推广城市：">
                            <el-select v-model="item.city" class="ex_input_y mr10" placeholder="市" @focus="getProareaList(item.province,index,item.city)" @change="getcityList(item.province,index,item.city,2)" >
                                <el-option v-for="(items,key) in cityData" :key="key" :value="items.city"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-button style="margin-left: 20px;" type="primary" @click="delData_ex(item,index)">删除</el-button>
                    </div>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addPeopleDialog = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        proareaList,
        storeAsGet,
        storeAsPost,
        storeAsPut
    } from '../api/api';
    import {formatDate} from '../tool/tool';
    import {base64,tool_confirm} from '../tool/tool'
    export default {
        data() {
            return {
                //列表数据
                list:[],
                searchTime: 'ORDERTIME',
                startTime: '',
                endTime: '',
                findStartTimeValue: '',
                //分页
                // pageNum: null,
                // cur_page: 0,
                // pageSize: 10,
                //弹窗
                addPeopleDialog: false,
                addForm_data: {},
                data_extend: [],
                select_province: '',
                provinceData: [],
                cityData: [],
                trueForm: {

                },
                memId: '',
                currentRow: '',
                //详情
                activeName: 'member',
                activeShow: true,
                pickerOptions: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            const end = new Date();
                            end.setTime(end.getTime());
                            end.setHours(23);
                            end.setMinutes(59);
                            end.setSeconds(59);
                            console.log(end,115);
                            end.setTime(end.getTime());
                            const start = new Date();
                            start.setHours(0);
                            start.setMinutes(0);
                            start.setSeconds(0);
                            start.setTime(start.getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    },{
                        text: '昨天',
                        onClick(picker) {
                            const end = new Date();
                            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
                            end.setHours(23);
                            end.setMinutes(59);
                            end.setSeconds(59);
                            console.log(end,115);
                            end.setTime(end.getTime());
                            const start = new Date();
                            start.setHours(0);
                            start.setMinutes(0);
                            start.setSeconds(0);
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                            picker.$emit('pick', [start, end]);
                        }
                    },{
                        text: '最近7天',
                        onClick(picker) {
                            const end = new Date();
                            end.setHours(23);
                            end.setMinutes(59);
                            end.setSeconds(59);
                            end.setTime(end.getTime());
                            const start = new Date();
                            start.setHours(0);
                            start.setMinutes(0);
                            start.setSeconds(0);
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近30天',
                        onClick(picker) {
                            const end = new Date();
                            end.setHours(23);
                            end.setMinutes(59);
                            end.setSeconds(59);
                            end.setTime(end.getTime());
                            const start = new Date();
                            start.setHours(0);
                            start.setMinutes(0);
                            start.setSeconds(0);
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近90天',
                        onClick(picker) {
                            const end = new Date();
                            end.setHours(23);
                            end.setMinutes(59);
                            end.setSeconds(59);
                            end.setTime(end.getTime());
                            const start = new Date();
                            start.setHours(0);
                            start.setMinutes(0);
                            start.setSeconds(0);
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 89);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
            }
        },
        created() {
            this.dataSelectFn();
            this.getProareaList();
            // this.getworkerList();
        },
        computed: {
        },
        methods: {
            // 时间类型
            timeSelectFn(val){
                this.searchTime = val;
                this.getworkerList();
            },
            dataSelectFn(data){//日期搜索列表
                let startTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss').substring(0,10) + ' 00:00:00';
                let endTime = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss').substring(0,10) + ' 23:59:59';
                if(!data){
                    let data = []
                    data[0] = startTime;
                    data[1] = endTime;
                    this.startTime = data[0];
                    this.endTime = data[1];
                    this.findStartTimeValue = data;
                }else{
                    this.startTime = formatDate(data[0], 'yyyy-MM-dd hh:mm:ss');
                    this.endTime = formatDate(data[1], 'yyyy-MM-dd hh:mm:ss');
                }
                this.getworkerList();

            },
            //列表展示
            getworkerList(){
                storeAsGet(
                    'promote/worker/list/all?timeType='+this.searchTime
                    +'&startTime='+this.startTime
                    +'&endTime='+this.endTime
                ).then(res => {
                    console.log(res,"101")
                    // 赋值
                    this.list = res.data.content.list;
                    this.salcTotalObj = {
                        addWechatNumAll : 0,
                        dereceiveNumAll : 0,
                        repeatNumAll : 0,
                        errorNumAll : 0,
                        invalidNumAll : 0
                    }

                    Array.prototype.slice.call(this.list).forEach((value,index)=>{
                        value.dereceiveNum = value.receiveNum + value.addWechatNum + value.invalidNum + value.tailAfterNum + value.errorNum + value.repeatNum;
                        value.somereceiveNum = value.receiveNum + value.addWechatNum + value.invalidNum + value.tailAfterNum;
                        let rateMon = value.dereceiveNum - value.repeatNum - value.errorNum - value.invalidNum;
                        let ratesMon = value.dereceiveNum - value.repeatNum - value.errorNum;

                            this.salcTotalObj.addWechatNumAll += value.addWechatNum
                            this.salcTotalObj.dereceiveNumAll += value.dereceiveNum
                            this.salcTotalObj.repeatNumAll += value.repeatNum
                            this.salcTotalObj.errorNumAll += value.errorNum
                            this.salcTotalObj.invalidNumAll += value.invalidNum

                        if(rateMon == 0 || value.dereceiveNum == 0 || ratesMon == 0){
                            value.rate = Number(0).toFixed(2)+"%";
                            value.rateAll = Number(0).toFixed(2)+"%";
                        }else{
                            value.rate = Number((value.addWechatNum / (value.dereceiveNum - value.repeatNum - value.errorNum - value.invalidNum))*100).toFixed(2)+"%";
                            value.rateAll = Number((value.addWechatNum / (value.dereceiveNum - value.repeatNum - value.errorNum))*100).toFixed(2)+"%";
                        }
                    });
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                });
            },
            getProareaList(val,index,city){
                console.log(val,city,index,"getProareaList")
                proareaList().then(res => {
                    this.provinceData = res.data.content.provinceList;
                });
                if(city){
                    if(val){
                        this.getcityList(val,index,city,1);
                    }
                }else{
                    this.getcityList(val,index,'',4);
                }

            },
            getcityList(val,index,city,flag){
                console.log(val,index,city,flag,"cityData")
                storeAsGet('/promote/area/province/city?province='+val).then(res => {
                    if(flag == 4){
                        this.cityData = res.data.content.promoteAreaList;
                        this.data_extend[index] = {
                            name: this.addForm_data.name,
                            province: val,
                            city: this.cityData[0].city,
                            proArea_id: this.cityData[0].id,
                        }
                    }else if(flag == 1){
                        this.cityData = res.data.content.promoteAreaList;
                        this.data_extend[index] = {
                            name: this.addForm_data.name,
                            province: val,
                            city: city,
                            proArea_id: this.cityData[0].id,
                        }
                    }else{
                        this.cityData = res.data.content.promoteAreaList;

                        this.cityData.map(item=>{
                            console.log(item,"item")
                            if(city == item.city){
                                this.data_extend[index] = {
                                    name: this.addForm_data.name,
                                    province: val,
                                    city: city,
                                    proArea_id: item.id,
                                }
                                // this.getCityID()
                            }
                        })
                    }

                    // this.getCityID(val,this.cityData[0].city,index);
                    console.log(this.data_extend,"145")
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                });
            },
            //删除
            delData_ex(item, index) {
                // console.log(item, index,"item, index")
                console.log(this.data_extend,"before")
                for (var i = 0; i < this.data_extend.length; i++) {
                    if (this.data_extend.length >= 0) {
                        if (index == i) {
                            if(this.data_extend[index]){
                                this.data_extend[index].name = '';
                                this.data_extend[index].province = '';
                                this.data_extend[index].city = '';
                                this.data_extend[index].proArea_id = '';
                            }
                            this.data_extend.splice(i,1);
                            console.log(this.data_extend,"after")
                        }
                    }
                }
            },
            // 修改
            editFn(index,val){
                this.data_extend = [];
                this.addPeopleDialog = true;
                this.memId = val.id;
                console.log(val);
                storeAsGet(
                    'promote/worker/detail?promoteWorkerId='+val.id
                ).then(res => {
                    console.log(res,"282")
                    // 赋值
                    this.addForm_data = res.data.content.promoteWorkerView;
                    console.log(this.addForm_data.promoteAreaWorkerRelationList,"promoteAreaWorkerRelationList")
                    this.addForm_data.promoteAreaWorkerRelationList.map(item=>{
                        // console.log(item.promoteArea)
                        this.data_extend.push({
                            name: this.addForm_data.name,
                            province:item.promoteArea.province,
                            city:item.promoteArea.city,
                            proArea_id: item.promoteArea.id,
                        })
                    })
                    console.log(this.data_extend);
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                });
                // addForm_data
            },
            //添加负责区域
            addData_ex() {
                this.data_extend.push({
                    name: this.addForm_data.name,
                    province: '',
                    city: ''
                });
                console.log('addData_ex')
            },
            // 保存编辑
            saveEdit() {
                console.log(this.data_extend,"this.data_extend");
                let testArr = [];
                let newTestArr = [];
                let pickids = [];
                this.data_extend.map(item=>{
                    testArr.push(item.proArea_id)
                    pickids.push({promoteArea:{id:item.proArea_id}})
                })
                newTestArr = Array.from(new Set(testArr))
                console.log(newTestArr,"testArr");
                if(newTestArr.length != testArr.length){
                    this.$message.error("有重复添加区域！")
                    return false;
                }
                this.trueForm = {
                    promoteAreaWorkerRelationList: pickids,
                }
                // console.log(this.trueForm,"trueForm")
                storeAsPut('/promote/worker/detail?promoteWorkerId='+this.memId, this.trueForm).then(res=>{
                    this.addPeopleDialog = false;
                    this.$message.success(`修改成功`);
                    // this.getGroupList();
                }).catch(errors=>{
                    this.$message.error(errors.response.data.detail)
                });
            },
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                // this.getStoreList(val-1)
            },

            handleSelectionChange(val) {
                // console.log(val,"handleSelectionChange")
                // this.multipleSelection = val;
            },
            handleSizeChange(val){
                // console.log(val,111111)
            },
        /* 重写计算总数 */
        getSummaries(param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计"
                    return
                }
                /* 计算成交率的 key 标识 */
                if (column.property == "rate" || column.property == "rateAll") {
                    let totalObj = this.salcTotalObj
                    console.log(totalObj)
                    if(!totalObj){
                        return false
                    }
                    let temp = totalObj.dereceiveNumAll - totalObj.repeatNumAll - totalObj.errorNumAll - totalObj.invalidNumAll
                    let tempAll = totalObj.dereceiveNumAll - totalObj.repeatNumAll - totalObj.errorNumAll
                    if(column.property == "rate"){
                        console.log()
                        if(temp == 0){
                            sums[index] = '0.00%'
                            return 
                        }
                        sums[index] = Number((totalObj.addWechatNumAll / temp) * 100 ).toFixed(2) + "%"
                                
                    }else{
                        if(tempAll == 0){
                            sums[index] = '0.00%'
                            return 
                        }
                        sums[index] = Number((totalObj.addWechatNumAll / tempAll) * 100).toFixed(2) + "%"
                    }
                    return
                }
                const values = data.map(item => Number(item[column.property]))
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr)
                        if (!isNaN(value)) {
                            return prev + curr
                        } else {
                            return prev
                        }
                    }, 0)
                    sums[index] += ""
                } else {
                    sums[index] = ""
                }
            })

            return sums
        },
        }
    }
</script>

<style scoped>
    .store{
        position: relative;
    }
    .store .store_title{
        height: 40px;
    }
    .store .store_title div{
        line-height: 40px;
    }
    .store .mainBtn{
        position: absolute;
        right: 0;
        top:0
    }
    .sp-divleft{
        display: inline-block;
        width: 10%;
    }
    .sp-div{
        display: inline-block;
        width: 80%;
    }
    .sp-btn{
        height: 40px;
        padding: 0 20px;
        line-height: 40px;
        font-size: 20px;
    }
    .extend_form{
        width: 540px;
        margin-left: 15px;
    }
    .ex_input_city{
        width: 150px;
    }
    .ex_parent{
        width: 240px;
        display: inline-block;
        padding:10px;
        border:1px solid #c0ccda;
        margin: 5px 5px 5px 0;
    }
    .ex_input_f,.ex_input_y{
        width: 120px;
    }
    .ex_input_tip{
        display: inline-block;
        font-size: 12px;
        color: red;
    }
    .ex-tag{
        font-size: 14px;
        margin-right: 5px;
        margin-bottom: 5px;
    }
</style>
